/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.gwt.client.sec.content.group;

import han.bifang.gwt.client.common.Content;
import han.bifang.gwt.client.common.ContentChangeListener;
import han.bifang.gwt.client.common.GwtContext;
import han.bifang.gwt.client.common.PrivilegChecker;
import han.bifang.gwt.client.common.RequestObject;
import han.bifang.gwt.client.common.ResponseObject;
import han.bifang.gwt.client.common.Searchable;
import han.bifang.gwt.client.common.entity.Usergroup;
import han.bifang.gwt.client.common.util.StringUtils;
import han.bifang.gwt.client.communicate.BifangGWTServiceAsync;
import han.bifang.gwt.client.sec.SecurityContentConstants;
import han.bifang.gwt.client.sec.SecurityMessages;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.ColumnFormatter;

/**
 * 
 * @Author Kent
 */
public class GroupMgmtContent extends Content implements Searchable {
	private SecurityMessages cons = null;

	private BifangGWTServiceAsync service = null;

	private GwtContext context = null;

	private VerticalPanel panel;

	private SimplePanel result = null;

	private TextBox groupName;

	private int size = 10;

	private int currentPage = 1;

	private boolean loaded;

	private AsyncCallback<ResponseObject> cb = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}

			ArrayList ret = (ArrayList) res.getResponse();
			int total = (Integer) ret.get(0);
			// Window.alert("total " + total);
			ArrayList list = (ArrayList) ret.get(1);
			if (total != 0) {
				VerticalPanel v = new VerticalPanel();
				v.setWidth("100%");
				v.setSpacing(5);

				Grid table = new Grid(list.size() + 1, 3);
				table.setWidth("60%");
				table.setCellPadding(1);
				table.setCellSpacing(1);
				table.setBorderWidth(1);

				ColumnFormatter cf = table.getColumnFormatter();

				cf.setWidth(0, "30%");
				cf.setWidth(1, "55%");
				cf.setWidth(2, "15%");

				CellFormatter ff = table.getCellFormatter();
				ff.setStyleName(0, 0, "tablecol");
				ff.setStyleName(0, 1, "tablecol");
				ff.setStyleName(0, 2, "tablecol");

				table.setHTML(0, 0, cons.groupName());
				table.setHTML(0, 1, cons.description());
				table.setHTML(0, 2, "&nbsp");

				for (int i = 1, j = list.size() + 1; i < j; i++) {
					Usergroup s = (Usergroup) list.get(i - 1);
					table.setHTML(i, 0, s.getGroupName());
					table.setHTML(i, 1,
							StringUtils.isEmpty(s.getDescription()) ? "&nbsp"
									: s.getDescription());

					Button b = new Button(cons.view());
					ViewClickListener l = new ViewClickListener();
					l.setContentChangeListener(listener);
					l.setId(s.getId());
					b.addClickListener(l);

					table.setWidget(i, 2, b);

				}
				v.add(table);
				v.add(new HTML("&nbsp;"));
				HorizontalPanel h = new HorizontalPanel();
				h.setWidth("60%");
				h.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
				h.add(new HTML(cons.page(total, currentPage)));
				v.add(h);
				if (total > 1) {

					if (currentPage > 1) {
						Button pre = new Button(cons.previous());
						pre.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
								currentPage--;
								searchGroup(currentPage, size);
							}

						});
						// h.add(new HTML("&nbsp;&nbsp;"));
						h.add(pre);
					}
					if (currentPage < total) {
						Button n = new Button(cons.next());
						n.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
								currentPage++;
								searchGroup(currentPage, size);
							}

						});
						// h.add(new HTML("&nbsp;&nbsp;"));
						h.add(n);

					}

				}
				result.setWidget(v);

			} else {
				result.setWidget(new HTML(cons.noResult()));
			}
		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	public GroupMgmtContent(SecurityMessages cons,
			BifangGWTServiceAsync service, GwtContext context) {
		this.service = service;
		this.context = context;
		this.cons = cons;

		panel = new VerticalPanel();
		panel.setWidth("100%");
		initWidget(panel);

	}

	public void onLoad() {
		if (!loaded) {
			Button create = new Button(cons.createGroup());
			create.addClickListener(new ClickListener() {

				public void onClick(Widget sender) {
					listener.onContentChanged(
							SecurityContentConstants.GROUP_MGMT,
							SecurityContentConstants.CREATE_GROUP, null);

				}

			});
			if (PrivilegChecker.hasPrivilege(context, null))
				panel.add(create);
			panel.add(new HTML("&nbsp;"));

			Grid table = new Grid(2, 2);
			table.setWidth("60%");
			table.setCellPadding(1);
			table.setCellSpacing(1);
			table.setBorderWidth(1);

			ColumnFormatter cf = table.getColumnFormatter();
			cf.setWidth(0, "33%");
			cf.setWidth(1, "33%");

			CellFormatter ff = table.getCellFormatter();
			ff.setStyleName(0, 0, "tablecol");
			ff.setStyleName(0, 1, "tablecol");

			table.setHTML(0, 0, cons.groupName());
			table.setHTML(0, 1, "&nbsp;");

			groupName = new TextBox();
			groupName.setVisibleLength(32);

			Button search = new Button(cons.search());
			search.addClickListener(new ClickListener() {

				public void onClick(Widget sender) {
					searchGroup(currentPage, size);

				}
			});

			table.setWidget(1, 0, groupName);
			table.setWidget(1, 1, search);

			panel.add(table);
			panel.add(new HTML("&nbsp;"));

			panel.add(new HTML(cons.userList()));
			result = new SimplePanel();
			result.setWidth("100%");
			panel.add(result);
			result.add(new HTML(cons.noResult()));
			// searchGroup(currentPage, size);
			loaded = true;
		}
	}

	private void searchGroup(int page, int size) {
		RequestObject req = new RequestObject();
		req.setAction("han.bifang.gwt.server.action.sec.SearchGroupAction");
		ArrayList p = new ArrayList();
		HashMap<String, String> param = new HashMap<String, String>();
		if (!StringUtils.isEmpty(groupName.getText()))
			param.put("groupName", groupName.getText());

		p.add(param);
		p.add(page);
		p.add(size);
		req.setRequest(p);
		service.call(req, cb);
	}

	private static class ViewClickListener implements ClickListener {
		private ContentChangeListener listener;
		private String id;

		public void setContentChangeListener(ContentChangeListener l) {
			listener = l;
		}

		public void setId(String id) {
			this.id = id;
		}

		public void onClick(Widget sender) {
			HashMap p = new HashMap();
			p.put("id", id);

			listener.onContentChanged(
					SecurityContentConstants.SEARCH_GROUP_RESULT,
					SecurityContentConstants.GROUP_DETAIL, p);

		}

	}

	public void refresh() {
		searchGroup(currentPage, size);

	}
}
